package com.srwl.mytx.widget;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.activity.LoginActivity;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.adapter.TopicDonationRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Donation;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.DonationService;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.utils.Utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TopicDonationView extends LinearLayout implements TopicDonationRecordAdapter.InteractionListener {
    private static final String TAG = "DonationView";
    @BindView(R.id.btn_donation)
    Button btn_donation;
    @BindView(R.id.tv_show_more_donation_record)
    TextView tv_showMoreDonationRecord;
    @BindView(R.id.rv_donation)
    RecyclerView rv_donation;
    @BindView(R.id.tv_donation_count)
    TextView tv_donationCount;
    @BindView(R.id.tv_donation_amount)
    TextView tv_donationAmount;
    @BindView(R.id.tv_donation_balance)
    TextView tv_donationBalance;
    @BindView(R.id.tv_tips)
    TextView tv_tips;
    @BindView(R.id.rl_donation_balance)
    RelativeLayout rl_donation_balance;
    private TopicDonationRecordAdapter donationRecordAdapter;
    private int donationPage = 1;
    private int donationSize = 10;
    private boolean hasNextPage = true;
    ArrayList<Donation> donationList = new ArrayList<>();
    private double receivedDonationAmount;//收到的捐赠总金额
    private double donationBalance;
    private Integer donationCount;
    private Context context;
    private String topicId;
    private Topic topic;
    private InteractionListener listener;
    public boolean isDonationUpdate = false; //标记是否刷

    public TopicDonationView(Context context) {
        super(context);
        this.context = context;
        inflate(context, R.layout.donation_view, this);
        ButterKnife.bind(this);
    }

    public TopicDonationView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        inflate(context, R.layout.donation_view, this);
        ButterKnife.bind(this);

    }

    public void init(Topic topic, InteractionListener listener) {
        init(topic);
        donationList.clear();
        donationPage = 1;
        this.listener = listener;
        donationRecordAdapter = new TopicDonationRecordAdapter(context, donationList, this);
        rv_donation.setLayoutManager(new LinearLayoutManager(context, RecyclerView.VERTICAL, false));
        rv_donation.setAdapter(donationRecordAdapter);
        // rv_donation.setNestedScrollingEnabled(false);
        tv_showMoreDonationRecord.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData();

//                TopicReceivedDonationRecord topicReceivedDonationRecord = TopicReceivedDonationRecord.newInstance(donationList,topicId,totalDonationAmount,donationCount);
//                topicReceivedDonationRecord.show(((FragmentActivity) context).getSupportFragmentManager(), "");
            }
        });
        btn_donation.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                DonationDialog_1 donationDialog_1=new DonationDialog_1(TopicDetailsActivity.this);
//                donationDialog_1.show();
                if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                    context.startActivity(new Intent(context, LoginActivity.class).putExtra("EXTRA_CONTENT", "捐赠需要先登录"));
                    return;
                }
                if (topic.getType() == Constant.TOPIC_TYPE_REWARD) {
                    Integer status = topic.getStatus();
                    if (status != null) {
                        if ((status == Constant.TOPIC_STATUS_REWARD_COMPLETE)) {
                            ConfirmDialog dialog = new ConfirmDialog(context, "提示", "悬赏已完成，不再接受捐赠");
                            dialog.show();
                            return;
                        }
                        if ((status == Constant.TOPIC_STATUS_REWARD_CANCEL)) {
                            ConfirmDialog dialog = new ConfirmDialog(context, "提示", "悬赏已取消，不再接受捐赠");
                            dialog.show();
                            return;
                        }
                    }
                } else if (topic.getType() == Constant.TOPIC_TYPE_EXPOSE && topic.getuId().equals(UserProfileManager.getInstance().getUserID())) {
                    //曝光类主题中，主题的发起者不能给自己的主题捐款，因为曝光类主题捐款后会直接存入发起者的余额中
                    Toast.makeText(context, "曝光主题中是无法给自己捐款哦！", Toast.LENGTH_SHORT).show();
                    return;
                }

                //final User myUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
                NumberInputDialog donationDialog = NumberInputDialog.newInstance();
                donationDialog.setConfirmListener(new NumberInputDialog.ConfirmListener() {
                    @Override
                    public void confirm(final Double amount) {
                        Log.d(TAG, "confirm: amount:" + amount);
                        new PayUtils(context, amount, "捐赠 将从账户余额中扣除", new PayUtils.InteractionListener() {
                            @Override
                            public void onPrepareComplete(String payPassword) {
                                donation(amount, payPassword, topic);
                            }
                        });

                    }
                });
                donationDialog.show(((FragmentActivity) context).getSupportFragmentManager(), "");
            }
        });
        tv_tips.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String content;

                if (topic.getType() == Constant.TOPIC_TYPE_REWARD) {
                    content = "收到的捐赠将会追加到赏金中，如果悬赏取消，捐赠将会原路返回，如果悬赏成功，则会转发给赏金获得者；在捐赠转发之前可以拆回";
                } else if (topic.getType() == Constant.TOPIC_TYPE_EXPOSE) {
                    content = "收到的捐赠将直接入账至曝光发起者的账户余额中，作为对曝光发起者的鼓励，不可拆回";
                } else {
                    content = context.getString(R.string.donation_tips_for_focus);
                }
                ConfirmDialog dialog = new ConfirmDialog(context, "说明", content);
                dialog.show();
            }
        });

        loadData();
    }

    public void init(Topic topic) {
        this.topic = topic;
        if (topic.getType() == Constant.TOPIC_TYPE_EXPOSE || topic.getType() == Constant.TOPIC_TYPE_REWARD) {
            rl_donation_balance.setVisibility(GONE);
        }
        if (topic.getDonationReceived() != null) {
            receivedDonationAmount = topic.getDonationReceived();
        }
        if (topic.getDonationBalance() != null) {
            donationBalance = topic.getDonationBalance();
        }
        topicId = topic.getId();

       // btn_donation.setText("捐赠");
        tv_donationAmount.setText(Utils.moneyFormat(receivedDonationAmount));
        tv_donationBalance.setText(Utils.moneyFormat(donationBalance));
//        if (isDonationUpdate) {
//            //更新前,清空捐赠的数据
//            donationList.clear();
//            donationPage = 1;
//            loadData();
//            isDonationUpdate = false;
//        }
    }


    public void setSize(int size) {
        donationSize = size;
    }

    /**
     * 查询主题下面的捐赠记录
     */
    public void loadData() {
        if (!Helper.getInstance().isNetworkConnected()) {
            listener.onLoadDonationComplete();
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, Object> body = new HashMap<>();
        body.put("page", donationPage);
        body.put("size", donationSize);
        body.put("topicId", topicId);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .queryTopicDonations(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (listener != null) {
                            listener.onLoadDonationComplete();
                        }
                        analysisResponse(response);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (listener != null) {
                            listener.onLoadDonationComplete();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    void analysisResponse(Response<CommonResult> response) {
        CommonResult result = response.body();
        if (!response.isSuccessful() || result == null) {
            Log.e(TAG, "onResponse: " + response.message());
            return;
        }
        if (result.isError()) {
            Log.e(TAG, "onResponse: " + result.getMsg());
            return;
        }
        JSONObject pageInfo = (JSONObject) result.getData();
        Log.d(TAG, "onResponse: 获取捐赠数据完成：" + pageInfo.toJSONString());
        donationCount = pageInfo.getInteger("total");
        tv_donationCount.setText(donationCount + "");
        hasNextPage = pageInfo.getBoolean("hasNextPage");
        if (!hasNextPage && listener != null) {
            listener.onHaveNotMoreData();
        }
        List<Donation> donations = pageInfo.getJSONArray("list").toJavaList(Donation.class);
        donationList.addAll(donations);
        donationRecordAdapter.notifyDataSetChanged();
        donationPage++;
    }


    void donation(final double donationAmount, String payPassword, Topic topic) {
        final Donation donation = new Donation();
        donation.setAmount(donationAmount);
        Map<String, Object> body = new HashMap<>();
        body.put("donation", donation);
        if (!TextUtils.isEmpty(payPassword)) {
            body.put("payPassword", payPassword);
        }
        donation.setoId(topicId);//捐给主题，需要设置主题id
        if (topic.getType() == Constant.TOPIC_TYPE_EXPOSE) {
            //曝光类型主题中的捐赠
            donation.setType(Constant.DONATION_TYPE_TO_EXPOSURE);
            donation.settId(topic.getuId());
            donationToExposure(donation, body);
        } else {
            donation.setType(topic.getType()); //主题的类型和捐赠类型是一致的
            donationToTopic(donation, body);
        }
    }

    private void donationToTopic(final Donation donation, Map<String, Object> body) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        listener.showProgressBar(true);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .donationToTopic(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        listener.showProgressBar(false);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            listener.showToast(context.getString(R.string.system_busy));

                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {

                                case Constant.BALANCE_NOT_ENOUGH:
                                    listener.showToast(context.getString(R.string.balance_not_enough));
                                    break;
                                case Constant.NO_PAY_PASSWORD:
                                    //这样的情况，应该不会发生，因为发起请求前，做了判断
                                    listener.showToast("没有支付密码");

                                    break;
                                case Constant.NEED_SETUP_PAY_PASSWORD_BEFORE:
                                    //这样的情况，应该不会发生，因为发起请求前，做了判断
                                    listener.showToast("还没有设置支付密码");
                                    break;
                                case Constant.PAY_PASSWORD_ERROR:

                                    listener.showToast(getContext().getString(R.string.pay_password_error));

                                    break;
                                case Constant.GET_LOCK_FAIL:
                                case Constant.UNKNOWN_ERROR:
                                    listener.showToast(context.getString(R.string.system_busy));
                                    break;
                                case Constant.TOPIC_STATUS_ERROR:
                                    //topic.setStatus(Constant.TOPIC_STATUS_REWARD_COMPLETE);

                                    // ((Activity) context).setResult(Activity.RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TOPIC, topic));
                                    listener.showToast(result.getMsg());
                                    btn_donation.setEnabled(false);
                                    btn_donation.setText("捐赠");
                                    break;
                                default:
                                    listener.showToast(context.getString(R.string.system_busy));
                            }
                            return;
                        }
                        JSONObject data = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 捐赠完成" + data.toJSONString());
                        double totalBalance = data.getDouble("balance");
                        //更新本地余额
                        UserProfileManager.getInstance().setUserBalance(totalBalance);
                        donation.setStatus(Constant.DONATION_STATUS_COULD_REVOKE);//补充捐赠的状态
                        if (data.containsKey("historyDonation")) {
                            Donation historyDonation = data.getObject("historyDonation", Donation.class);
                            historyDonation.setTargetUser(UserProfileManager.getInstance().getLoginUserInfo());
                            showDonation(historyDonation);
                        } else {
                            String donationId = data.getString("donationId");
                            firstDonation(donationId, donation);
                        }
                        receivedDonationAmount += donation.getAmount();
                        donationBalance += donation.getAmount();
                        tv_donationAmount.setText(Utils.moneyFormat(receivedDonationAmount));
                        tv_donationBalance.setText(Utils.moneyFormat(donationBalance));
                        listener.onCommitDonationComplete(receivedDonationAmount, donationBalance);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        listener.showProgressBar(false);
                        listener.showToast(context.getString(R.string.system_busy));
                    }
                });
    }


    /**
     * 非第一次捐赠
     *
     * @param historyDonation
     */
    private void showDonation(Donation historyDonation) {

        boolean hasHistory = false;
        for (int i = 0; i < donationList.size(); i++) {
            Donation donation1 = donationList.get(i);
            if (TextUtils.equals(donation1.getId(), historyDonation.getId())) {
                donationList.remove(i);
                historyDonation.setHasPraise(donation1.getHasPraise());   //后端historyDonation返回的数据不完整，需要补充
                historyDonation.setPraiseSize(donation1.getPraiseSize());
                donationList.add(0, historyDonation);
                //判断历史捐赠是否处于第一个位置，如果不是，需要替换一下位置
                if (i != 0) {
                    donationRecordAdapter.notifyItemMoved(i, 0);
                }
                donationRecordAdapter.notifyItemChanged(0);
                hasHistory = true;
                break;
            }
        }
        if (!hasHistory) {
            donationList.add(0, historyDonation);
            donationRecordAdapter.notifyItemInserted(0);
        }
    }

    /**
     * 个人第一次对该主题捐赠
     *
     * @param donationId
     * @param donation
     */
    private void firstDonation(String donationId, Donation donation) {
        donation.setId(donationId);
        donation.setTargetUser(UserProfileManager.getInstance().getLoginUserInfo());
        donation.setHasPraise(false);
        donation.setCreated(new Date());
        donationCount++;
        tv_donationCount.setText(donationCount + "");
        if (donationList.size() == 0) {
            donationList.add(donation);
            donationRecordAdapter.notifyDataSetChanged();
        } else {
            donationList.add(0, donation);
            donationRecordAdapter.notifyItemInserted(0);
        }
    }

    private void donationToPerson(final Donation donation, Map<String, Object> body) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        listener.showProgressBar(true);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .donationToPerson(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        listener.showProgressBar(false);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            listener.showToast(context.getString(R.string.system_busy));

                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {

                                case Constant.BALANCE_NOT_ENOUGH:
                                    listener.showToast(context.getString(R.string.balance_not_enough));
                                    break;
                                case Constant.NO_PAY_PASSWORD:
                                    //这样的情况，应该不会发生，因为发起请求前，做了判断
                                    listener.showToast("没有支付密码");

                                    break;
                                case Constant.NEED_SETUP_PAY_PASSWORD_BEFORE:
                                    //这样的情况，应该不会发生，因为发起请求前，做了判断
                                    listener.showToast("还没有设置支付密码");
                                    break;
                                case Constant.PAY_PASSWORD_ERROR:

                                    listener.showToast(getContext().getString(R.string.pay_password_error));

                                    break;
                                case Constant.GET_LOCK_FAIL:
                                case Constant.UNKNOWN_ERROR:
                                    listener.showToast(context.getString(R.string.system_busy));
                                    break;
                            }
                            return;
                        }
                        JSONObject data = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 捐赠完成" + data.toJSONString());
                        double totalBanaence = data.getDouble("balance");
                        //更新本地余额
                        UserProfileManager.getInstance().setUserBalance(totalBanaence);
                        donation.setTargetUser(UserProfileManager.getInstance().getLoginUserInfo());
                        donation.setHasPraise(false);
                        donationList.add(0, donation);
                        donationRecordAdapter.notifyDataSetChanged();
                        receivedDonationAmount += donation.getAmount();
                        donationBalance += donation.getAmount();
                        donationCount++;
                        tv_donationAmount.setText(Utils.moneyFormat(receivedDonationAmount));
                        tv_donationCount.setText(donationCount + "");
                        //showToast(btn_donation, getString(R.string.donation_complete));
                        listener.onCommitDonationComplete(receivedDonationAmount, donationBalance);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        listener.showProgressBar(false);
                        listener.showToast(context.getString(R.string.system_busy));
                    }
                });
    }

    /**
     * Exposure主题的捐赠逻辑
     */
    private void donationToExposure(final Donation donation, Map<String, Object> body) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        listener.showProgressBar(true);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .donationToExposure(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        listener.showProgressBar(false);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.d(TAG, "onResponse: " + response.message());
                            listener.showToast(context.getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            switch (result.getStatus()) {

                                case Constant.BALANCE_NOT_ENOUGH:
                                    listener.showToast(context.getString(R.string.balance_not_enough));
                                    break;
                                case Constant.NO_PAY_PASSWORD:
                                    //这样的情况，应该不会发生，因为发起请求前，做了判断
                                    listener.showToast("没有支付密码");

                                    break;
                                case Constant.NEED_SETUP_PAY_PASSWORD_BEFORE:
                                    //这样的情况，应该不会发生，因为发起请求前，做了判断
                                    listener.showToast("还没有设置支付密码");
                                    break;
                                case Constant.PAY_PASSWORD_ERROR:

                                    listener.showToast(getContext().getString(R.string.pay_password_error));

                                    break;
                                case Constant.GET_LOCK_FAIL:
                                case Constant.UNKNOWN_ERROR:
                                    listener.showToast(context.getString(R.string.system_busy));
                                    break;
                            }
                            return;
                        }
                        JSONObject data = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 捐赠完成" + data.toJSONString());
                        double totalBalance = data.getDouble("balance");
                        //更新本地余额
                        UserProfileManager.getInstance().setUserBalance(totalBalance);
                        String donationId = data.getString("donationId");
                        donation.setStatus(Constant.DONATION_STATUS_COULD_NOT_REVOKE);//补充捐赠的状态
                        firstDonation(donationId, donation);
                        receivedDonationAmount += donation.getAmount();
                        tv_donationAmount.setText(Utils.moneyFormat(receivedDonationAmount));
                        listener.onCommitDonationComplete(receivedDonationAmount, null);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        listener.showProgressBar(false);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        listener.showToast(context.getString(R.string.system_busy));
                    }
                });
    }


    public boolean isHasNextPage() {
        return hasNextPage;
    }

    @Override
    public void onItemViewClick(String forwardId) {
    }


    public interface InteractionListener {

        void showToast(String message);

        void showProgressBar(boolean isShowProgressBar);

        void onLoadDonationComplete();

        void onHaveNotMoreData();

        void onCommitDonationComplete(Double totalDonationAmount, Double donationBalance);
    }

}
